package com.bjpowernode.boss.common.cilent;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Component
public class RedisClient{
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    public boolean setHashAll(String key, Map<String,String> value, int timeout, TimeUnit unit){
        stringRedisTemplate.opsForHash().putAll(key, value);
        Boolean add = stringRedisTemplate.hasKey(key);
        if(timeout>0){
            add=stringRedisTemplate.expire(key,timeout,unit);
        }
        return add;
    }
    public String getFieldValue(String key,String field){
        Object FieldValue =  stringRedisTemplate.opsForHash().get(key,field);
        return (String)FieldValue;
    }
    public String getValue(String key){
        return  stringRedisTemplate.opsForValue().get(key);
    }
    public void setValue(String key,String value){
        stringRedisTemplate.opsForValue().set(key,value,300,TimeUnit.SECONDS);
    }
    public <T> List<T> get(String key,Class<T> t){
        List<T> list = new ArrayList<>();
        String menuJSON=getValue(key);
        if(StrUtil.isNotBlank(menuJSON)) {
            list = JSONUtil.toList(menuJSON, t);
        }
        return list;
    }
    public <T> boolean set(String key,T t){
        stringRedisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(t),300,TimeUnit.SECONDS);
        return Boolean.TRUE.equals(stringRedisTemplate.hasKey(key));
    }
    public Boolean deleteValue(String key){
        return stringRedisTemplate.delete(key);
    }
}
